﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Linq;
using System.Reflection;

namespace GuoZhiQi.MiddleCache.Common.Serialization
{
    public class JsonEnumNameAttribute : Attribute
    {
        public string Name { get; protected set; }

        public JsonEnumNameAttribute(string name)
        {
            this.Name = name;
        }
    }

    /// <summary>
    /// A specialized type converter which will convert any enum type into the string
    /// specified in the JsonEnumNameAttribute attribute.
    /// </summary>
    public class JsonEnumConverter<T> : StringEnumConverter
        where T : struct, IConvertible
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsEnum;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                string[] allValues = Enum.GetNames(typeof(T));
                if (allValues.Contains(existingValue.ToString()))
                    return base.ReadJson(reader, objectType, existingValue, serializer);
                else
                {
                    foreach (string enVal in allValues)
                    {
                        Enum realValue = (Enum)Enum.Parse(typeof(T), enVal);
                        if (realValue.GetStringValue() == existingValue.ToString())
                            return realValue;
                    }
                }
            }

            return base.ReadJson(reader, objectType, existingValue, serializer);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Type enumType = value.GetType();
            FieldInfo field = enumType.GetField(value.ToString());
            // Get the stringvalue attributes
            JsonEnumNameAttribute[] attribs = field.GetCustomAttributes(
                typeof(JsonEnumNameAttribute), false) as JsonEnumNameAttribute[];

            string writerValue = attribs != null ? attribs[0].Name : value.ToString();
            writer.WriteValue(writerValue);
        }
    }

}
